package cn.uniquesoft.service.impl;

import cn.uniquesoft.search.SearchDao;
import cn.uniquesoft.service.ISearchService;
import cn.uniquesoft.vo.SearchVO;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author:朱元勋
 * @mail:395910063@qq.com
 * @date:2018-11-12 10:53:20
 * @description:
 **/
@Service
public class SearchServiceImpl implements ISearchService {

    @Autowired
    private SearchDao dao;

    @Override
    public void save(SearchVO item) {
        this.dao.save(item);
    }

    @Override
    public void edit(String tid, String tname, String tvalue) {
        SearchVO item = new SearchVO();
        item.setId(tid+"_"+tname);
        item.setTvalue(tvalue);
        this.dao.save(item);
    }

    @Override
    public void remove(String tid, String tname) {
        this.dao.deleteById(tid+"_"+tname);
    }

    @Override
    public List<SearchVO> query(String tvalue,int start) {
        QueryBuilder queryBuilder = QueryBuilders.wildcardQuery("tvalue","*"+tvalue+"*");
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(queryBuilder).build();
        //分页
        searchQuery.setPageable(PageRequest.of(start-1,10));
        Page<SearchVO> searchResult = dao.search(searchQuery);
        return searchResult.getContent();
    }
}
